package com.yangchoi.jetpackcompose.ui.baseui

import android.util.Log
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Popup
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.yangchoi.jetpackcompose.R

@Composable
fun BaseComposePage(
    onCreate:(()->Unit)? = null,
    onResume:(()->Unit)? = null,
    onPause:(()->Unit)? = null,
    onDestroy:(()->Unit)? = null,
    bgColor: Color = Color.White,
    topBarContent: @Composable (() -> Unit)? = null,
    showLoading:Boolean = false,
    loadingText:String = "加载中....",
    content:@Composable ()->Unit
){
    val lifecycleOwner = LocalLifecycleOwner.current
    val lifecycleState = remember { mutableStateOf(Lifecycle.State.INITIALIZED) }
    val isInForeground = remember { mutableStateOf(true) }

    // todo ============================================================================生命周期监听 start====================
    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_CREATE -> {
                    lifecycleState.value = Lifecycle.State.CREATED
                }
                Lifecycle.Event.ON_RESUME -> {
                    isInForeground.value = true
                    lifecycleState.value = Lifecycle.State.RESUMED
                }
                Lifecycle.Event.ON_PAUSE -> {
                    isInForeground.value = false
                }
                Lifecycle.Event.ON_DESTROY -> {
                    lifecycleState.value = Lifecycle.State.DESTROYED
                }
                else -> Unit
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)

        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }
    LaunchedEffect(lifecycleState.value) {
        when(lifecycleState.value){
            Lifecycle.State.RESUMED -> {
                Log.d("lifecycleStateTAG","OnResume")
                onResume?.invoke()
            }
            Lifecycle.State.CREATED -> {
                Log.d("lifecycleStateTAG","OnCreate")
                onCreate?.invoke()
            }
            Lifecycle.State.DESTROYED -> {
                Log.d("lifecycleStateTAG","OnDestroy")
                onDestroy?.invoke()
            }
            else -> Unit
        }
    }
    // todo ============================================================================生命周期监听 end====================

    // todo 应用处于前后台监听 start
    LaunchedEffect(isInForeground.value) {
        if (isInForeground.value) {
            // 执行进入前台时的操作
            Log.d("isInForeground","进入前台")
        }
    }

    // 例如，在离开前台时执行某个操作
    SideEffect {
        if (!isInForeground.value) {
            // 执行离开前台时的操作
            Log.d("isInForeground","进入后台")
            onPause?.invoke()
        }
    }
    // todo 应用处于前后台监听 end

    // page content
    BaseScaffold(bgColor = bgColor, topBarContent = topBarContent) {
        content()
    }

    // loading content
    if (showLoading){
        LoadingContent(isLoading = showLoading, loadingText = loadingText)
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun BaseScaffold(bgColor:Color = Color.White,topBarContent: @Composable (() -> Unit)? = null,content:@Composable () -> Unit,){
    Scaffold(topBar = {
        if (topBarContent != null){
            topBarContent()
        }
    }) { innerPadding ->
        Column(modifier = Modifier
            .padding(innerPadding)
            .fillMaxSize()
            .background(color = bgColor)) {
            content()
        }
    }
}

@Composable
private fun LoadingContent(isLoading:Boolean,loadingText:String){
    val transition = rememberInfiniteTransition()
    val rotation by transition.animateFloat(
        initialValue = 0f,
        targetValue = 360f,
        animationSpec = infiniteRepeatable(
            animation = tween(durationMillis = 2000, easing = LinearEasing),
            repeatMode = RepeatMode.Restart
        )
    )
    Popup {
        Box(modifier = Modifier.fillMaxSize().background(color = Color.Gray.copy(alpha = 0.5f))){
            Column(modifier = Modifier
                .width(80.dp)
                .align(Alignment.Center)
                .background(color = Color.Black, shape = RoundedCornerShape(12.dp))) {
                Column(modifier = Modifier
                    .padding(top = 10.dp)
                    .size(40.dp)
                    .animateContentSize()
                    .align(Alignment.CenterHorizontally)){
                    AnimatedVisibility(
                        visible = isLoading,
                        enter = fadeIn() + expandVertically(),
                        exit = fadeOut() + shrinkVertically()
                    ) {
                        Image(
                            painter = painterResource(id = R.mipmap.icon_loading),
                            contentDescription = "Loading...",
                            modifier = Modifier.rotate(rotation),
                            colorFilter = ColorFilter.tint(color = Color.White)
                        )
                    }
                }
                Text(text = loadingText, style = TextStyle(color = Color.White, fontSize = 14.sp), modifier = Modifier
                    .padding(top = 5.dp, bottom = 10.dp)
                    .align(Alignment.CenterHorizontally))
            }
        }
    }
}